<?php

/**
 * Class SqliteCacher
 */
class SqliteCacher implements ICacher
{
    /**
     * @var string
     */
    protected $file = './places.db';
    /**
     * @var SQLite3
     */
    protected $database;
    /**
     * @var
     */
    protected $live_time = CACHE_LIVE_TIME;

    /**
     *
     */
    public function __construct()
    {
        $this->database = new SQLite3($this->file);
        if (!$this->database) {
            throw new Exception("Unable to create a DB");
        }
        $this->database->exec('CREATE TABLE IF NOT EXISTS places (query_key int, result text, created timestamp DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (query_key));');
    }

    /**
     * @param $key
     * @return null
     */
    public function get($key)
    {
        $result = $this->database->query("SELECT result, created FROM places WHERE query_key='{$key}'");
        if ($result instanceof SQLite3Result) {
            $result = $result->fetchArray(SQLITE3_ASSOC);
            if ((time() - $result['created']) > $this->live_time) {
                return null;
            }
            return $result['result'];
        }
        return null;
    }

    /**
     * @param $key
     * @param $value
     * @param int $time
     */
    public function set($key, $value, $time = 0)
    {
        $this->database->exec("INSERT OR REPLACE INTO places (query_key, result, created) VALUES ('{$key}', '{$value}', '" . time() . "')");
    }
}
